package wpmp.portal.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import wcommons.httputils.ResponseUtils;
import wcommons.httputils.quickbean.RespInfo;
import wcommons.lang.quickbean.Message;
import wpmp.portal.service.UserService;
import wpmp.security.client.internal.SecurityUtils;
import wpmp.security.client.utils.UserUtils;

/**
 * @author Wayne.Wang<5waynewang@gmail.com>
 * @since 11:49:23 AM Dec 5, 2013
 */
@Controller
@RequestMapping("/updatePassword.do")
public class UpdatePasswordController extends BaseController {

	@Autowired
	private UserService service;

	@RequestMapping(method = { RequestMethod.GET, RequestMethod.POST })
	public void updatePassword(HttpServletRequest req, HttpServletResponse resp,
			@RequestParam(value = "password", required = true) String password,
			@RequestParam(value = "newPassword", required = true) String newPassword) throws Exception {
		final String securityId = SecurityUtils.getSecurityId(req);
		if (StringUtils.isBlank(securityId)) {
			ResponseUtils.renderJson(resp, Message.getErrorMessageString("请重新登录"));
			return;
		}

		final String loginName = UserUtils.getLoginName(req);
		final RespInfo<Object> respInfo = service.updatePassword(loginName, password, newPassword, securityId);
		if (respInfo == null) {
			ResponseUtils.renderJson(resp, Message.getErrorMessageString("网络错误，请联系管理员"));
		}
		else if (respInfo.isSuccess()) {
			ResponseUtils.renderJson(resp, Message.getNoteMessageString("密码修改成功"));
		}
		else if (respInfo.getCode() == 501) {
			ResponseUtils.renderJson(resp, Message.getErrorMessageString("原密码不正确，请重新输入"));
		}
		else {
			ResponseUtils.renderJson(resp, Message.getErrorMessageString("密码修改失败"));
		}
	}
}
